<%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%>
var rootTable;
$(function(){
	$("#startDate").datebox({
		onSelect : function() {//datebox把onHidePanel换成onSelect
			onChangeStartTime();
	    }
	});

	$("#endDate").datebox({
		onSelect : function() {//datebox把onHidePanel换成onSelect
			onChangeEndTime();
	    }
	});
	
	//表格加载
	rootTable=$('#superviseListTable').datagrid({
	    url:'<c:url value="/supervise/superviseListDateFirstPart" />',
	    queryParams:getParams(''),//提交参数
	    showHeader:false,
	    //toolbar:'#superviseListToolbar',//表头工具栏
	    pagination:true,//显示分页  
	    pagePosition:'bottom',//分页栏出现位置
	    pageNumber:1,//初始页码
	    pageSize:10,//初始每页显示记录数量
	    nowrap: false,//设置内容多时换行，false换行
	    singleSelect:true,
	    columns:[[
			{field:'docId',title:'',width:"80%",formatter: function(value,row,index){
				return (row.displayNumber==""?"":("<font color='blue'>（"+row.displayNumber+"）</font>"))+
				(row.endTime==null?"":"<font color='red'>（"+dataFormatStr(new Date(row.endTime),"yyyy-MM-dd")+"）</font>")+row.docName;
			}},
			{field:'operationState',title:'操作',width:"20%",formatter: function(value,row,index){
				return value=="1"?"已完成":"<a href='javascript:closeSupervise(\""+row.docId+"\")'>完成</a>";
			},hidden:"<c:out value='${node}' />"!="root"},
			
	    ]],
	    rowStyler:function(index,row){
	    	return "font-weight:bold";
	    },
	    onClickCell: function (rowIndex, field, value) {
	    	IsCheckFlag = false;
		},
		onSelect: function (rowIndex, rowData) {
			if (!IsCheckFlag) {
				IsCheckFlag = true;
				rootTable.datagrid("unselectRow", rowIndex);
			}
			rootTable.datagrid("expandRow",rowIndex);
			//rootTable.datagrid('collapseRow', rowIndex);
		},
		onLoadSuccess:function(data){
			if(data.total>0){
				rootTable.datagrid("expandRow",0);
				setTimeout(function(){
					rootTable.datagrid("resize");
				},1000);
			}
		},
	    view: detailview,
	    detailFormatter:function(index,row){
			return '<div><table id="ddv-' + index + '"></table></div>';
		},
		onExpandRow: function(parentIndex,parentRow){
			$('#ddv-'+parentIndex).datagrid({
				url:"<c:url value='/supervise/superviseListDateSecondPart'/>",
				queryParams:getParams(parentRow.docId),//提交参数
				fitColumns:true,
				singleSelect:true,
				rownumbers:true,
				//loadMsg:'',
				height:'auto',
				columns:[[
					{field:'docName',title:'事项名称',width:"25%",align:'left',halign:'center'},
					{field:'draftOrg',title:'承办部门',width:"15%",align:'center',halign:'center'},
					{field:'transactor',title:'承办人',width:"10%",align:'center',halign:'center'},
					{field:'limitTime',title:'限办时间',width:"10%",align:'center',halign:'center',formatter: function(value,row,index){
						return value?dataFormatStr(new Date(value),"yyyy-MM-dd"):"";
					}},
					{field:'docState',title:'当前状态',width:"15%",align:'center',halign:'center',formatter: function(value,row,index){
						if(value==null || value=="" || value=="DR"){
							return "未提交反馈";
						}else if(value=="TR"){
							return "反馈审批中";
						}else if(value=="BR"){
							return "已提交反馈";
						}else if(value=="TM"){
							return "已废止";
						}else if(value=="DE"){
							return "已收回";
						}
					}},
					{field:'bak1',title:'操作',width:"15%",align:'center',halign:'center',formatter: function(value,row,index){
						value=row.docState;
						if("<c:out value='${node}' />"=="root"){
							if(parentRow.operationState!="1"){
								if(value==null || value=="" || value=="DR"){
									return "<a href=\"javascript:urgeBranchDate('"+parentIndex+"','"+row.docId+"','1');\">催办</a>\t<a href=\"javascript:endBranch('"+parentIndex+"','"+row.docId+"');\">终止</a>\t<a href=\"javascript:callBackBranch('"+parentIndex+"','"+row.docId+"');\">收回</a>";
								}else if(value=="TR"){
									return "<a href=\"javascript:showDetails('"+parentIndex+"','"+row.docId+"','0');\">查看</a>\t<a href=\"javascript:endBranch('"+parentIndex+"','"+row.docId+"');\">终止</a>";
								}else if(value=="BR"){
									return "<a href=\"javascript:showDetails('"+parentIndex+"','"+row.docId+"','0');\">查看</a>";
								}else if(value=="DE"){
									return "<a href=\"javascript:updateBranch('"+parentIndex+"','"+row.docId+"');\">修改</a>\t<a href=\"javascript:reSendBranch('"+parentIndex+"','"+row.docId+"');\">重发</a>";
								}
							}else{
								if(value=="TR" || value=="BR"){
									return "<a href=\"javascript:showDetails('"+parentIndex+"','"+row.docId+"','0');\">查看</a>";
								}
							}
						}else{
							if(parentRow.operationState!="1"){
								if(value==null || value=="" || value=="DR"){
									var str="";
									if("<c:out value='${personId}' />"==row.transactorCode){
										if(row.transferTransactorCode==null || row.transferTransactorCode==""){
											str="<a href=\"javascript:transfer('"+parentIndex+"','"+row.docId+"');\">转办</a>\t<a href=\"javascript:showDetails('"+parentIndex+"','"+row.docId+"','1');\">办理</a>";
										}else{
											str="<a href=\"javascript:urgeBranchDate('"+parentIndex+"','"+row.docId+"','0');\">催办</a>\t<a href=\"javascript:showDetails('"+parentIndex+"','"+row.docId+"','0');\">查看</a>";
										}
										str+="\t<a href=\"javascript:submitIssue('"+parentIndex+"','"+row.formId+"','"+row.docId+"');\">提交</a>";
									}else{
										str="<a href=\"javascript:showDetails('"+parentIndex+"','"+row.docId+"','1');\">办理</a>";
									}
									return str;
								}else if(value=="TR" || value=="BR"){
									str="<a href=\"javascript:showDetails('"+parentIndex+"','"+row.docId+"','0');\">查看</a>";
								}
							}else{
								if(value=="TR" || value=="BR"){
									str="<a href=\"javascript:showDetails('"+parentIndex+"','"+row.docId+"','0');\">查看</a>";
								}
							}
							return "";
						}
					}}
				]],
				onResize:function(){
					rootTable.datagrid('fixDetailRowHeight',parentIndex).datagrid("resize");
				},
				onLoadSuccess:function(){
					setTimeout(function(){
						rootTable.datagrid('fixDetailRowHeight',parentIndex).datagrid("resize");
					},1000);
				}
			});
		}
	});
	
	//查询按钮绑定点击事件
	$("#searchButton").click(function(){ 
		rootTable.datagrid({ queryParams:getParams('')});
	});
	
	$("#transferDiv").dialog({
		title:"请选择办理人员",//标题
		width: 250,//宽度
	    height: 350,//高度
	    closed: true,//初始关闭
	    modal: true,
	    onClose: function() {
	    	$("#transferForm").find("input[type='hidden']").val("");
	    	$("#transferForm").find("input[name='transferTransactorCode']:checked").prop("checked",false);
			},
		buttons:[{
			text:'确认',
			handler:function(){
				if($("input[name='transferTransactorCode']:checked").size()==0){
					$.messager.alert("提示",'请选择一个办理人员后再操作');
				}else{
					$.blockUI({ 
						message: '<img src="<c:url value="/images/busy.gif"/>" />&nbsp;&nbsp;<span>正在执行操作 请稍候...</span>', 
						css:{color: '#E17009',fontSize:'17px',padding:'10px'},
						onBlock:function(){
							$.ajax({           
						        type: "POST",                 
						        url: "<c:url value='/supervise/transfer'/>",                  
						        data: $('#transferForm').serialize(),        
						        dataType: 'json',      
								async:false,            
						        timeout: 5000,                  
						        error: function() {
						        	$.messager.alert("提示",'操作失败');
						        },                  
						        success: function(json) {
						        	if(json.state=="200"){
						        		freshView($("#transferForm").find("#index").val());
							        	$("#transferDiv").dialog("close");
						        	}else{
						        		$.messager.alert("提示",'操作失败');
						        	}
						         }              
							});	
							$.unblockUI();
						}});
				}
			}
		},{
			text:'取消',
			handler:function(){
				$("#transferDiv").dialog("close");
			}
		}]
	});
	
	$("#editBranchDiv").dialog({
		title:"督办事项详情",//标题
		width: 950,//宽度
	    height: 450,//高度
	    closed: true,//初始关闭
	    modal: true,
	    cache: false//缓存
	});
	
	$("#updateBranchDiv").dialog({
		title:"修改督办事项",//标题
		width: 650,//宽度
	    height: 180,//高度
	    closed: true,//初始关闭
	    modal: true,
	    cache: false//缓存
	});
});

function getParams(parentId){
	var jsonObj=new Object();
	if($('input[name="orgCode"]').size()==1 && $('input[name="orgCode"]').val()!=""){
		jsonObj.orgCode=$('input[name="orgCode"]').val();
	}
	if($('input[name="state"]').val()!=""){
		jsonObj.state=$('input[name="state"]').val();
	}
	if($('input[name="startDate"]').val()!=""){
		jsonObj.startDate=$('input[name="startDate"]').val()+" 00:00:00";
	}
	if($('input[name="endDate"]').val()!=""){
		jsonObj.endDate=$('input[name="endDate"]').val()+" 23:59:59";
	}
	if(parentId && parentId!=""){
		jsonObj.parentId=parentId;
	}
	jsonObj.node="<c:out value='${node}' />";
	return jsonObj;
}
function freshView(index){
	rootTable.datagrid('collapseRow', index).datagrid("expandRow",index);
}
function transfer(index,docId){
	if(isNotBlank(index) && isNotBlank(docId)){
		if(checkState(docId,"DR")){
			$("#transferForm").find("#index").val(index);
			$("#transferForm").find("#docId").val(docId);
			$("#transferDiv").window("center").dialog("open");
		}else{
			freshView(index);
		}
	}else{
		$.messager.alert("提示",'获取数据错误，请刷新页面后重试');
	}
}
function showDetails(index,docId,editFlag){
	if(isNotBlank(docId) && isNotBlank(index)){
		if(editFlag=="1" && checkState(docId,"DR") || editFlag=="0"){
			if(editFlag=="1"){
				$.ajax({           
			        type: "POST",                 
			        url: "<c:url value='/supervise/checkForm'/>",             
			        dataType: 'json',      
					async:false,            
			        timeout: 5000,                  
			        error: function() {
			        	$.messager.alert("提示",'操作失败');
			        },                  
			        success: function(json) {
			        	if(json.state=="200"){
			        		if(!json.formId){
			        			$.messager.alert("提示",'您所在单位没有创建督办处理单，请联系相关人员添加后再操作');
			        			return;
			        		}
			        		if(!json.hasPermissions || json.hasPermissions=="0"){
			        			$.messager.alert("提示",'您所在部门没有督办处理单拟稿权限，请联系相关人员添加后再操作');
			        			return;
			        		}
			        		$("#editBranchDiv").dialog('refresh', '<c:url value="/supervise/superviseDeptShow" />?docId='+docId+"&formId="+json.formId+"&editFlag="+editFlag+"&index="+index).window("center").dialog("open");
			        	}else{
			        		$.messager.alert("提示",'操作失败');
			        	}
			         }              
				});
			}else{
				$("#editBranchDiv").dialog('refresh', '<c:url value="/supervise/superviseDeptShow" />?docId='+docId+"&formId=&editFlag="+editFlag+"&index="+index).window("center").dialog("open");
			}	
		}else{
			freshView(index);
		}
	}else{
		$.messager.alert("提示",'获取数据错误，请刷新页面后重试');
	}
}
function closeDetails(index){
	$("#editBranchDiv").dialog("close");
	if(index){
		freshView(index);
	}
}
function submitIssue(index,formId,docId){
	if(isNotBlank(formId) && isNotBlank(docId) && isNotBlank(index)){
		/*var vHeight = window.screen.height -80 ;
		var wordUrl =_synergyContext+"/basic/flowItem/"+formId+"/isNew?issueId="+docId;
		var winFeatures = "height="+vHeight+"px,width="+(window.screen.width-20)+"px,top=0,left=0,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no";
		window.open(wordUrl,'_blank',winFeatures);*/
		if(checkState(docId,"DR")){
			window.location.href=_synergyContext+"/basic/flowItem/"+formId+"/isNew?issueId="+docId;
		}else{
			freshView(index);
		}
	}else{
		freshView(index);
		$.messager.alert("提示",'请确认是否已经办理此事项督办，或者刷新本页面后重试');
	}
}

function urgeBranchDate(index,docId,sendAll){
	if(isNotBlank(docId) && isNotBlank(index)){
		if(checkState(docId,"DR")){
			$.ajax({           
		        type: "POST",                 
		        url: "<c:url value='/supervise/urgeBranchDate'/>",   
		        data:"docId="+docId+"&type=1&sendAll="+sendAll,       
		        dataType: 'json',      
				async:false,            
		        timeout: 5000,                  
		        error: function() {
		        	$.messager.alert("提示",'操作失败');
		        },                  
		        success: function(json) {
		        	if(json.state=="200"){
		        		$.messager.alert("提示",'催办发送成功');
		        	}else{
		        		$.messager.alert("提示",'操作失败');
		        	}
		        	}});
		}else{
			freshView(index);
		}
	}else{
		$.messager.alert("提示",'获取数据错误，请刷新页面后重试');
	}
}

function callBackBranch(index,docId){
	if(isNotBlank(index) && isNotBlank(docId)){
		if(checkState(docId,"DR")){
			$.messager.confirm('提示', '确定要收回此事项么？', function(r){
				if (r){

					$.ajax({           
				        type: "POST",                 
				        url: "<c:url value='/supervise/callBackBranch'/>",   
				        data:"docId="+docId,       
				        dataType: 'json',      
						async:false,            
				        timeout: 5000,                  
				        error: function() {
				        	$.messager.alert("提示",'操作失败');
				        },                  
				        success: function(json) {
				        	if(json.state=="200"){
				        		freshView(index);
				        	}else{
				        		$.messager.alert("提示",'操作失败');
				        	}
				        	}});
				}
			});
		}else{
			freshView(index);
		}
	}else{
		$.messager.alert("提示",'获取数据错误，请刷新页面后重试');
	}
}

function reSendBranch(index,docId){
	if(isNotBlank(index) && isNotBlank(docId)){
		if(checkState(docId,"DE")){
			$.ajax({           
		        type: "POST",                 
		        url: "<c:url value='/supervise/reSendBranch'/>",   
		        data:"docId="+docId,       
		        dataType: 'json',      
				async:false,            
		        timeout: 5000,                  
		        error: function() {
		        	$.messager.alert("提示",'操作失败');
		        },                  
		        success: function(json) {
		        	if(json.state=="200"){
		        		freshView(index);
		        	}else{
		        		$.messager.alert("提示",'操作失败');
		        	}
		        	}});
		}else{
			freshView(index);
		}
	}else{
		$.messager.alert("提示",'获取数据错误，请刷新页面后重试');
	}
}

function endBranch(index,docId){
	if(isNotBlank(index) && isNotBlank(docId)){
		if(checkState(docId,"DRTR")){
			$.messager.confirm('提示', '确定要终止此事项么？', function(r){
				if (r){
					$.ajax({           
				        type: "POST",                 
				        url: "<c:url value='/supervise/endBranch'/>",   
				        data:"docId="+docId,       
				        dataType: 'json',      
						async:false,            
				        timeout: 5000,                  
				        error: function() {
				        	$.messager.alert("提示",'操作失败');
				        },                  
				        success: function(json) {
				        	if(json.state=="200"){
				        		freshView(index);
				        	}else{
				        		$.messager.alert("提示",'操作失败');
				        	}
				        	}});
				}
			});
		}else{
			freshView(index);
		}
	}else{
		$.messager.alert("提示",'获取数据错误，请刷新页面后重试');
	}
}

function checkState(docId,compareState){
	var flag=false;
	if(isNotBlank(docId) && isNotBlank(compareState)){
		$.ajax({           
	        type: "POST",                 
	        url: "<c:url value='/supervise/getState'/>",   
	        data:"docId="+docId,       
	        dataType: 'json',      
			async:false,            
	        timeout: 5000,                  
	        error: function() {
	        	$.messager.alert("提示",'操作失败');
	        },                  
	        success: function(json) {
	        	if(json.state=="200"){
	        		if(compareState=="DRTR" && (json.docState==null || json.docState=="" || json.docState=="DR" || json.docState=="TR") //终止操作时比对状态（未提交反馈状态、反馈审批中）
	        				|| compareState=="DR" && (json.docState==null || json.docState=="" || json.docState=="DR") //比对未提交反馈状态
	        				|| compareState==json.docState){//比对其他状态
	        			flag=true;
	        		}else{
	        			if(json.docState=="TR"){
	        				$.messager.alert("提示",'操作失败，该事项督办当前正处于‘反馈审批中’状态');
	        			}else if(json.docState=="BR"){
	        				$.messager.alert("提示",'操作失败，该事项督办当前正处于‘已提交反馈’状态');
	        			}else if(json.docState=="TM"){
	        				$.messager.alert("提示",'操作失败，该事项督办当前正处于‘已废止’状态');
	        			}else if(json.docState=="DE"){
	        				$.messager.alert("提示",'操作失败，该事项督办当前正处于‘已收回’状态');
	        			}
	        		}
	        		
	        	}else{
	        		$.messager.alert("提示",'操作失败');
	        	}
	        	}});
	}else{
		$.messager.alert("提示",'获取数据错误，请刷新页面后重试');
	}
	return flag;
}

function isNotBlank(value){
	return value != null && value !="null" && value != "" && value != undefined;
}

function closeSupervise(docId){
	if(isNotBlank(docId)){
		$.messager.confirm('提示', '是否确定所有待办事项都已经执行完毕?', function(r){
			if (r){
				$.ajax({           
			        type: "POST",                 
			        url: "<c:url value='/supervise/closeSupervise'/>",   
			        data:"docId="+docId,       
			        dataType: 'json',      
					async:false,            
			        timeout: 5000,                  
			        error: function() {
			        	$.messager.alert("提示",'操作失败');
			        },                  
			        success: function(json) {
			        	if(json.state=="200"){
			        		$('#superviseListTable').datagrid({ queryParams:getParams('')});
			        	}else{
			        		$.messager.alert("提示",'操作失败');
			        	}
			        	}});
			}
		});
		
	}else{
		$.messager.alert("提示",'获取数据错误，请刷新页面后重试');
	}
}
/**
 * 本方法用于督办部门收回后修改
 * @param index
 * @param docId
 * @returns
 */
function updateBranch(index,docId){
	if(isNotBlank(index) && isNotBlank(docId)){
		$("#updateBranchDiv").dialog('refresh', '<c:url value="/superviseBranch/alterBranchPage" />?docId='+docId+"&index="+index).window("center").dialog("open");
	}else{
		$.messager.alert("提示",'获取数据错误，请刷新页面后重试');
	}
}

function closeBranchDetails(index){
	$("#updateBranchDiv").dialog("close");
	if(index){
		freshView(index);
	}
}

function onChangeStartTime(){
	var startTime = $("#startDate").val();//开始时间
	var endTime = $("#endDate").val();//结束时间
	if(startTime!=null&&startTime!=""&&endTime!=null&&endTime!=""){
		if(startTime>endTime){
			 $.messager.alert('提示','开始时间不能大于结束时间!');
			 $('#startDate').datebox('setValue', ''); 
			 return;
		}
	}	
}

function onChangeEndTime(){
	var startTime = $("#startDate").val();//开始时间
	var endTime = $("#endDate").val();//结束时间
	if(startTime!=null&&startTime!=""&&endTime!=null&&endTime!=""){
		if(startTime>endTime){
			 $.messager.alert('提示','开始时间不能大于结束时间!');
			 $('#endDate').datebox('setValue', ''); 
			 return;
		}
	}	
}